import cv2
import numpy as np


def add_rain(image, intensity=0.5, drop_length=20, drop_width=1, drop_color=(200, 200, 200)):
    """
    给图像添加雨的效果
    :param image: 输入的图像
    :param intensity: 雨的强度，范围0到1
    :param drop_length: 雨滴的长度
    :param drop_width: 雨滴的宽度
    :param drop_color: 雨滴的颜色
    :return: 添加雨效果后的图像
    """
    rows, cols, _ = image.shape
    num_drops = int(intensity * rows * cols * 0.0005)

    for _ in range(num_drops):
        x = np.random.randint(0, cols)
        y = np.random.randint(0, rows)
        length = np.random.randint(int(drop_length * 0.5), drop_length)
        angle = np.random.uniform(-15, 15)
        end_x = np.clip(x + int(length * np.cos(angle * np.pi / 180)), 0, cols)
        end_y = np.clip(y + int(length * np.sin(angle * np.pi / 180)), 0, rows)
        cv2.line(image, (x, y), (end_x, end_y), drop_color, drop_width)

    return image


def add_fog(image, fog_strength=0.5):
    """
    给图像添加雾的效果
    :param image: 输入的图像
    :param fog_strength: 雾的强度，范围0到1
    :return: 添加雾效果后的图像
    """
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    mean_gray = np.mean(gray)
    fog = np.ones_like(image) * int(mean_gray * fog_strength)
    foggy_image = cv2.addWeighted(image, 1 - fog_strength, fog, fog_strength, 0)
    return foggy_image


def reduce_light(image, factor=0.5):
    """
    降低图像的光线，模拟光线不足效果
    :param image: 输入的图像
    :param factor: 亮度降低因子，范围0到1
    :return: 光线不足效果的图像
    """
    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    h, s, v = cv2.split(hsv)
    v = np.clip(v * factor, 0, 255).astype(np.uint8)
    hsv = cv2.merge((h, s, v))
    new_image = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    return new_image


if __name__ == '__main__':
    # 读取图像
    img = cv2.imread(r"C:\Users\64531\Desktop\weed-datasets\allcorn weed datasets\bluegrass\images\bluegrass_0001.jpg")  # 请将 'your_image.jpg' 替换为你的图像路径

    # img_with_rain = add_rain(img, intensity=8.8)
    # cv2.imshow('Image with Rain', img_with_rain)

    img_with_fog = add_fog(img, fog_strength=0.7)
    cv2.imshow('Image with Fog', img_with_fog)

    # img_low_light = reduce_light(img, factor=0.3)
    # cv2.imshow('Image with Low Light', img_low_light)

    cv2.waitKey(0)
    cv2.destroyAllWindows()